import 'package:bili_caricature/pages/cubit/information/state.dart';
import 'package:bili_caricature/routers/home_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../base/base_list_view.dart';
import '../../../base/base_stateful_page.dart';
import '../../../routers/navigator_utils.dart';
import '../model/info_model.dart';
import '../widgets/info_item.dart';
import 'cubit.dart';

class MessageModulePage extends BasePage {
  const MessageModulePage({super.key});

  @override
  BasePageState<BasePage> getState() {
    return _MessageModulePageState();
  }
}

class _MessageModulePageState extends BasePageState<MessageModulePage> {
  /// 列表控制器
  final ScrollController scrollController = ScrollController();

  /// 刷新组建控制器
  final RefreshController refreshController = RefreshController(initialRefresh: false);

  /// 隐藏返回按钮
  @override
  Widget left() {
    return const SizedBox();
  }

  @override
  void initState() {
    super.initState();
    pageTitle = 'cubit-list';
    pageBgColor = const Color(0xFFF3F4F8);
    isBack = false;
  }

  @override
  void buildComplete() {
    _getData();
  }

  /// 请求数据
  _getData({bool? isRefresh = true}) {
    MessageModuleCubit cubit = context.read<MessageModuleCubit>();
    cubit.getListData(isRefresh: isRefresh);
  }

  /// 上拉加载
  void _onLoading() {
    _getData(isRefresh: false);
  }

  /// 下拉刷新
  void _onRefresh() {
    _getData();
  }

  Widget mainWidget(MessageModuleState state) {
    return BaseListView(
      refreshController: refreshController,
      scrollController: scrollController,
      bgColor: const Color(0xFFF3F4F8),
      enablePullDown: true,
      enablePullUp: true,
      data: state.dataList ?? [],
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      itemBuilder: (InfoModel model, int index) => InfoWidget(
        model: model,
        onTap: () {
          NavigatorUtils.push(context, HomeRouter.messageDetailPage, arguments: {
            'entityId': model.id,
          });
        },
      ),
    );
  }

  void _listener(BuildContext context, MessageModuleState state) {
    refreshController.refreshCompleted();
    refreshController.loadComplete();
    if (state.isNoMoreDataState == true) {
      refreshController.loadNoData();
    }
  }

  @override
  Widget buildPage(BuildContext context) {
    return BlocConsumer<MessageModuleCubit, MessageModuleState>(
      listener: _listener,
      listenWhen: (state1, state2) {
        if (state1.netLoadCount != state2.netLoadCount) {
          return true;
        }
        return false;
      },
      builder: (context, state) {
        return resultWidget(state, (baseState, context) => mainWidget(state), refreshMethod: () {
          _getData();
        });
      },
    );
  }
}
